package com.juefeng.SMS.listener.init.memery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContextEvent;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.juefeng.SMS.mapper.SmsConfigMapper;
import com.juefeng.SMS.pojo.SmsConfig;
import com.juefeng.common.jedisclient.impl.SingleJedisClient;

public class SMSconfigMemery {
	
	private SmsConfigMapper configMapper;
	private  SingleJedisClient jedisClient;
	private static SMSconfigMemery sconfigMemery = new SMSconfigMemery();
	private static Log log = LogFactory.getLog(SMSconfigMemery.class);
	private SMSconfigMemery(){
		
	}
	
	public static SMSconfigMemery getSMSconfigMemery(){
		return sconfigMemery;
	}
	
	public void addSMSConfigMemery(ServletContextEvent enent){
		ApplicationContext ac = WebApplicationContextUtils
	            .getWebApplicationContext(enent.getServletContext());
		this.configMapper = (SmsConfigMapper) ac.getBean("smsConfigMapper");
	    List<SmsConfig> list = configMapper.querySMSConfigList(new SmsConfig());
	    jedisClient = (SingleJedisClient) ac.getBean("singleJedisClient");
	    addToRedis(jedisClient,list, -1L);
	}
	
	
	public List<SmsConfig> updateSMSConfigMemery(Long sysTypeId){
		List<SmsConfig> list = configMapper.querySMSConfigList(new SmsConfig());
		List<SmsConfig> listById = addToRedis(jedisClient,list,sysTypeId);
		return listById;
	}

	private List<SmsConfig> addToRedis(SingleJedisClient jedisClient,List<SmsConfig> list,Long sysId) {
		log.info("-------------- add SmsConfig to redis start ---------------");
		HashMap<Long, ArrayList<SmsConfig>> cacheMap = new HashMap<Long,ArrayList<SmsConfig>>();
	    for (SmsConfig smsConfig : list) {
	    	if(cacheMap.containsKey(smsConfig.getSysTypeId())){
	    		cacheMap.get(smsConfig.getSysTypeId()).add(smsConfig);
	    		continue;
	    	}else{
	    		ArrayList<SmsConfig> arrayList = new ArrayList<SmsConfig>();
	    		arrayList.add(smsConfig);
	    		cacheMap.put(smsConfig.getSysTypeId(),arrayList);
	    	}
		}
	    
    	for (Long sysTypeId : cacheMap.keySet()) {
    		
    		JSONArray fromObject = JSONArray.fromObject(cacheMap.get(sysTypeId));
    		jedisClient.set("mSmsConfigSysId="+sysTypeId.toString(),fromObject.toString());
    	}
    	log.info("-------------- add SmsConfig to redis end ---------------");
		return cacheMap.get(sysId);
	}
	
}
